<template>
	<!-- 开始匹配游戏界面 -->

	<view class="bd">


		<view class="musicPlay">
			<image src="../../static/音乐(1).png" v-if="ifMusicPlay" class="musicPic" @click="clickPlay()"></image>
			<image src="../../static/暂停音乐.png" v-else class="musicPic" @click="clickPlay()"></image>
		</view>
		<!-- 进入答题时候的展示 -->
		<view class="bdMatched" v-if="ifMatch===true">

			<view class="RightWrongNumber" v-if="ifSingle">
				<!-- 展示答对或者答错的题目数-->
				<view class="right">
					答对：{{rightNumber}}
				</view>
				<view class="wrong">
					答错：{{wrongNumber}}
				</view>
			</view>
			<view class="progress-bar" :style="{display:ifSingle ? 'none': 'normal'}">
				<!-- 进度条展示双方的积分信息 -->
				<view class="progress" :style="{ width: progressWidth }">
					<text style="margin-left: 10rpx;">{{thePlayerL.scoreAll}}</text>
				</view>
				<view class="thePic">
					<image :src="thePlayerL.avatarurl"></image>
				</view>
			</view>
			<view class="progress-bar" :style="{display:ifSingle ? 'none': 'normal'}">
				<!-- 进度条展示双方的积分信息 -->
				<view class="progress1" :style="{ width: progressWidth1 } ">
					<text style="margin-left: 10rpx;"> {{thePlayerR.scoreAll}}</text>
				</view>
				<view class="thePic">
					<image :src="thePlayerR.avatarurl"></image>
				</view>
			</view>

			<view class="title">
				<view class="ts">
					<!-- 谜题猜什么 -->
					{{ ['填空题', '多选题', '单选题', '判断题'][fetchMsg.puzzleType] }} - {{ allGameTime }}
				</view>

				<view class="md">
					<view class="md-top">
						<text>{{ fetchMsg.puzzleName }}</text>

						<view class="countT">
							<text>{{ countdown }}</text>
						</view>
					</view>

					<view class="md-body">
						<!-- 谜题的题目 -->
						<view>
							<text>{{ fetchMsg.puzzleContentDTO.contentText }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 选择题的答案区域start -->
			<view class="answer">
				<!-- class="ItemInXuanZe" -->
				<view class="DuoXuan" v-if="fetchMsg.puzzleType === 1 || fetchMsg.puzzleType === 2">
					<view v-for="(item ,index) in fetchMsg.optionList" :key="index"
						@click="chooseAnswer(item.tbSelect,index)"
						:class=" item.ifActive==true ? 'ItemInXuanZeActive'  :  'ItemInXuanZe' ">
						<!-- 每个选项 -->
						<view class="ItemLeft">
							{{item.tbSelect}}.
						</view>

						<view class="ItemRight">
							{{item.selectContent}}
						</view>
					</view>
				</view>
				<!-- 填空题的答案区域start -->

				<input v-else class="TianKong" placeholder="输入答案" v-model="answer" hold-keyboard />

			</view>
			<!-- 选择题的答案区域end -->

			<view class="bottom-action" :style="{ transform: `translateY(-${keyboardHeight}px)` }">
				<!-- 按钮区域start -->
				<view class="btn" @click="sendMsg()" :class="{disabled:!answer}">
					下一题
				</view>
				<!-- 按钮区域end -->

				<!-- buff区域start -->
				<view class="buff">
					<ToastBuff :ChooseWho='ChooseWho' :canChoose='canChoose' :canChoose1='canChoose1'
						:canChoose2='canChoose2' @ChooseBuffSuccess='ChooseBuffSuccess' class="toastBufff"
						v-if="ifBuffGame" :class="{disabled:buffAdd}"></ToastBuff>
				</view>
				<!-- buff区域end -->
			</view>
		</view>


		<view class="bdToMatch" v-else>
			<!-- <view class="dount">

			</view> -->

			<!-- 等待的图标样式start -->
			<div class="loader"></div>
			<!-- 等待的图标样式end -->

			<view class="showPerMsg">
				<!-- 展示个人或者双方的信息，一人一半，决斗的样式 -->
				<view class="showPerMsgL">
					<image :src="thePlayerL.avatarurl" class="showPerMsgLP"></image>
					<view class="showPerMsgLT">
						{{thePlayerL.nickname}}
					</view>
				</view>
				<view class="VS">
					VS
				</view>
				<view class="showPerMsgR">
					<image :src="thePlayerR.avatarurl" class="showPerMsgLP" v-show="thePlayerR.nickname"></image>
					<view class="showPerMsgLT" v-show="thePlayerR.nickname">
						{{thePlayerR.nickname}}
					</view>
				</view>
			</view>
			<view class="text" v-if="!ifMatch">
				匹配中,请耐心等待...
			</view>
			<view class="text" v-else>匹配成功，等待进入...</view>
		</view>

		<!-- 游戏结束的画面，无论输赢 -->
		<GameEndComp @game-again='gameToAgain()' @game-giveup='gameToGiveup()' class="gameEEnd" v-if="gameEnd"
			:playerL="thePlayerL" :playerR='thePlayerR' ifWin='ifWin'></GameEndComp>
	</view>
	<!---->
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';

	// 导入游戏结束的组件
	import GameEndComp from '@/pages/models/endGameModel/endGameModel.vue'
	import ToastBuff from '@/pages/matchToSolve/toastBuff.vue';
	import {
		wxlogin,
		getPuzzleMoreMsg, //根据谜题id展示详细谜题信息

		getUserSomeMsg, //根据id获取用户简略信息
		checkPuzzleAnswer, //验证玩家答题信息
		getPuzzleByMsg, //条件展示简略谜题信息集合
	} from '@/config/api.js'



	import moment from 'moment';

	export default {
		components: {
			GameEndComp, //游戏结束的组件
			ToastBuff, //道具赛弹窗界面
		},

		data() {
			return {
				buffAdd: false, //是否可以发送buff
				buffWhich: '', //选中的buff的名称// “addTime”,"addClue","cutTime"
				canChoose: true, //是否可选
				canChoose1: true,
				canChoose2: true,


				ChooseWho: -1,

				rightNumber: 0,
				wrongNumber: 0,
				//单人游戏的时候，展示答对的题目数和答错的题目数

				needRequest: true, // 是否需要发送请求的标志位
				fetchMsg: {

				}, //抓取到的谜题 的数据
				answer: '', //填空题答案
				allGameTime: 300, //游戏的总时长

				SingleChatMessageDTO: {
					userId: -1,
					receiverId: -1,
					messageText: '',
					sendTime: '' // "yyyy-MM-dd HH:mm:ss"
				}, //发送的参数
				chatType: 'singlechat', //发送的参数


				ifMatch: false, //是否匹配完成，默认未匹配,有关页面的展示

				idsHasBeenUsed: [], //一个数组，存放使用过的谜题的ids
				//TODO1

				thePlayerL: {
					// scoreAll:0  //玩家目前得分
				}, //玩家左的信息，也就是自身玩家
				thePlayerR: {

				}, //玩家右的信息，也就是对面玩家


				socketTask: null, //websocket任务

				ifSocketOpen: false, //websocket任务是否开启

				fetchWebSocketMsg: {

				}, //接受到的服务器内容，匹配成功的时候返回的信息

				musicUrl: '', //音乐的播放地址

				innerAudioContext: null, //音频播放的组件，初始化为空
				ifMusicPlay: false,


				thePlayerAnswer: [], //玩家的答案
				isActice: [], //选择题是否被选择
				ifActive: [],
				count: 0, //选中的个数

				fetchMsg1: {}, //由star获取的数据，主要获取谜题 id

				theReturn: {}, //返回的结果，验证返回的结果
				count: 0, //判断是否是第一次进入，0表示第一次进入

				maxScore: 100, //进度条

				// countdown: 15, //15s进入下一题
				isAnswered: false, //是否已经回答
				loopId: null,

				tempRightScore: 0,
				firstTime: 0, //第一次匹配的；逻辑

				gameEnd: false,
				ifWin: false,

				ifSingle: false, //是否是单人游戏
				ifBuffGame: false, //是否是道具赛

				countdownValue: 0, // 用于存储可修改的数据

				buffs: [], //buffs集合默认为空

				keyboardHeight: 0,
			}
		},
		computed: {
			...mapState(['countdown', 'timer', 'countdownGame', 'timerGame', 'ifGameEnd']),

			showCountdown() {
				// 基于可修改的数据进行计算
				return this.countdownValue;
			},
			progressWidth() {

				console.log("this.thePlayerL.scoreAll---->" + this.thePlayerL.scoreAll)
				var ratio = Math.min(this.thePlayerL.scoreAll, this.maxScore) / this.maxScore; // 计算比值
				if (!this.thePlayerL.scoreAll) {
					ratio = 0
				}

				return `${ratio * 100}%`;
			},
			progressWidth1() {

				console.log("this.thePlayerR.scoreAll---->" + this.thePlayerR.scoreAll)
				var ratio = Math.min(this.thePlayerR.scoreAll, this.maxScore) / this.maxScore; // 计算比值
				if (!this.thePlayerR.scoreAll) {
					ratio = 0
				}

				return `${ratio * 100}%`;
			}
		},
		beforeDestroy() {
			if (!this.ifSingle) {
				this.socketTask.onClose(() => {
					console.log("已经被关闭了")
				})
			}

			this.destroyAudio()


			this.stopLoop()

			this.stopGlobalCountdown() //15秒倒计时停止计时
		},
		created() {
			this.giveupMatchFun()

			// 在页面加载时开始监听全局倒计时
			console.log("进入页面此时的countdown是==》" + JSON.stringify(this.countdown));
			this.countdownValue = this.countdown;

			this.fetchPlayerL() //进来就抓取自身 玩家信息


			// 在创建 Vue 实例后，使用 $watch 监测 myObject 中特定属性的变化
			this.$watch('thePlayerL.scoreAll', (newValue, oldValue) => {

				if (isNaN(newValue)) {
					this.thePlayerL.scoreAll = 0; // 当属性值为 NaN 时，赋值为 0
				}
				if (newValue <= 0 || newValue >= 100) {

					if (newValue <= 0) {
						//防止NAN出错
						this.thePlayerL.scoreAll = 0
					} else if (newValue >= 100) {
						this.thePlayerL.scoreAll = 100
					}
					this.endGameFun(); // 当属性值小于0时调用handleNegativeValue函数
				}
			});
			this.$watch('thePlayerR.scoreAll', (newValue, oldValue) => {

				if (isNaN(newValue)) {
					this.thePlayerR.scoreAll = 0; // 当属性值为 NaN 时，赋值为 0
				}
				if (newValue <= 0 || newValue >= 100) {

					if (newValue <= 0) {
						//防止NAN出错
						this.thePlayerR.scoreAll = 0
					} else if (newValue >= 100) {
						this.thePlayerR.scoreAll = 100
					}
					this.endGameFun(); // 当属性值小于0时调用handleNegativeValue函数
				}
			});
		},

		onUnload() {
			if (!this.ifSingle) {
				this.socketTask.onClose(() => {
					console.log("已经被关闭了")
				})
				this.giveupMatchFun()
			}


			this.destroyAudio() //销毁音乐

			uni.offKeyboardHeightChange(this.handleKeyboardHeightChange)

		},
		onLoad(options) {
			// 双人赛0，单人赛1，道具赛2
			const {
				index
			} = options
			console.log("传递过来的模式index是--》" + index)
			if (index == 1) {
				this.ifSingle = true
			} else if (index == 2) {
				this.ifBuffGame = true; //道具赛
			}

			//如果传递的是1，单人，则直接进入答题界面
			if (this.ifSingle == true) {
				console.log("目前游戏是单人模式。。。")
				this.ifMatch = true;

				//验证题目，收到消息==>，(立即)抓取题目,倒计时\
				this.getPuzzleFunSingle()
				if (this.ifGameEnd) {
					this.endGameFun()
				}
				//进来先判断是否有计时器,
				if (this.timerGame) {
					console.log("this.countdownGame==>" + this.countdownGame);
					this.allGameTime = parseInt(this.countdownGame); //记录剩余时间
				} else {
					//开始倒计时
					this.startGlobalGameCountdown() //开始全局计时
				}
				this.startCountdown1()


			} else {
				this.getMatchFun() //开始匹配,连接websocket
			}

			this.getMusicStart() //开始播放音乐


			this.getUserMsg() //调用函数，获取自身和对方玩家的信息

			uni.onKeyboardHeightChange(this.handleKeyboardHeightChange)
		},
		methods: {
			...mapMutations(['startGlobalCountdown',
				'stopGlobalCountdown', 'setCountdown',
				'setGameCountdown',
				'startGlobalGameCountdown',
				'stopGlobalGameCountdown'
			]),

			//选中buff的函数，即刻触发
			ChooseBuffSuccess(type) {
				console.log(type)
				if (type === 0) {
					this.buffWhich = 'addTime'
					this.ChooseWho = 0;
					
				} else if (type === 1) {
					this.buffWhich = 'addClue'
					this.ChooseWho = 1;

				} else if (type === 2) {
					this.buffWhich = 'cutTime'
					this.ChooseWho = 2;

				}
				console.log("Now the buffWhich is==>" + this.buffWhich)
				console.log("Now the buff is Choose is ==>" + type)

			},
			//单人赛的抓取函数
			getPuzzleFunSingle() {
				this.getPuzzleFun()
			},
			//退出
			gameToGiveup() {
				uni.navigateBack(1)
			},
			//重新开局
			gameToAgain() {
				uni.reLaunch({

					url: '/pages/matchToSolve/matchToSolve'


				})
			},
			// 游戏结束
			async endGameFun() {
				var that = this

				if (this.ifSingle) {
					//单人游戏的逻辑

				} else {
					//不是单人游戏的逻辑
					if (that.theReturn.player.ranking == 1 && that.theReturn !== {}) {
						console.log("//进入答过题目,游戏结束的逻辑")
						//1是第一名
						//游戏时间结束
						var Msg1 = {}

						// const res1 = await checkPuzzleAnswer(Msg1)
						Msg1.isSuccess = 2 //胜利的逻辑
						Msg1.puzzleId = that.fetchMsg1.id //谜题id
						Msg1.userId = that.$store.state.userInfo.id //玩家id
						// Msg1.buffs = that.buffs;
						Msg1.buffs = []
						Msg1.clueNumber = 0
						Msg1.ranking = 1 //排名
						Msg1.result = that.answer //玩家答题结果

						that.ifWin = true




						that.sendSocketMessage(Msg1) //发送websocket消息

						console.log("游戏结束了哦,且获得胜利==>")


					} else if (that.theReturn.player.ranking == 2 && that.theReturn !== {}) {
						console.log("游戏结束了哦,且失败了==>")
						var tempUser = {}
						tempUser = {
							...that.thePlayerL
						} //是输的
						that.thePlayerL = that.thePlayerR
						that.thePlayerR = tempUser
					}



				}
				uni.showToast({
					title: '游戏结束',
					icon: 'none'
				})
				//that.endGameFun()
				// that.stopLoop()
				that.stopGlobalCountdown()
				that.ifMatch = false
				that.stopGlobalGameCountdown()
				that.ifSingle = false;
				that.gameEnd = true; //游戏结束，进入结算界面


			},
			stopLoop() {
				clearInterval(this.loopId)
			},
			//倒计时函数
			async startCountdown1() {
				var that = this
				that.stopLoop() //先清除之前的计时器
				this.stopGlobalCountdown();

				if (this.loopId) {
					clearInterval(this.loopId)
				}

				this.startGlobalCountdown()

				this.loopId = setInterval(() => {

					if (this.countdown <= 1) {

						that.sendMsg() //提交 超时提交

						this.startCountdown1();
					}

					if (that.allGameTime <= 0) {
						uni.showToast({
							title: '游戏结束',
							icon: 'none'
						})
						that.endGameFun()
						that.stopLoop()
						that.stopGlobalCountdown()
						that.ifMatch = false
					} else {
						this.allGameTime--;
					}

				}, 1000)
			},


			//发送消息前的时间格式化
			fromatTime() {
				const date = new Date(); // 获取当前时间
				const dateString = moment(date).format('YYYY-MM-DDTHH:mm:ss');
				console.log(dateString); // 输出当前时间的字符串格式，
				this.SingleChatMessageDTO.sendTime = dateString
			},
			//选择题的答案的选择
			chooseAnswer(tbSelect, index) {
				var that = this
				console.log(tbSelect)
				console.log("index is --->" + index)
				// 如果是多选
				if (that.fetchMsg.puzzleType === 1) {
					// 使用 $set 方法更新数组中的元素
					this.$set(that.fetchMsg.optionList, index, {
						...that.fetchMsg.optionList[index],
						ifActive: !that.fetchMsg.optionList[index].ifActive
					})

					that.thePlayerAnswer = []
					that.fetchMsg.optionList.forEach((option) => {

						if (option.ifActive) {
							that.thePlayerAnswer.push(option.tbSelect)
						}
					})
					that.count = that.thePlayerAnswer.length
					console.log(that.fetchMsg.optionList)
					console.log("that.thePlayerAnswer==>" + JSON.stringify(that.thePlayerAnswer))
					// that.answer = that.thePlayerAnswer.join('')

					// var ArrayAnswer = that.thePlayerAnswer.split(",")
					that.answer = JSON.stringify(that.thePlayerAnswer)
				} else if (that.fetchMsg.puzzleType === 2) {
					//如果是单选

					this.$set(that.fetchMsg.optionList, index, {
						...that.fetchMsg.optionList[index],
						ifActive: !that.fetchMsg.optionList[index].ifActive
					})

					that.thePlayerAnswer = []
					let hasTrueOption = false; //是否已经选择过了
					that.fetchMsg.optionList.forEach((option, i) => {

						if (option.ifActive) {
							if (hasTrueOption) {
								that.$set(that.fetchMsg.optionList, i, {
									...that.fetchMsg.optionList[i],
									ifActive: false
								})
							}
							hasTrueOption = true
							that.thePlayerAnswer.push(option.tbSelect)
						}
					})
					that.count = that.thePlayerAnswer.length
					console.log(that.fetchMsg.optionList)
					console.log("that.thePlayerAnswer==>" + JSON.stringify(that.thePlayerAnswer))
					// that.answer = that.thePlayerAnswer.join('')

					// var ArrayAnswer = that.thePlayerAnswer.split(",")
					that.answer = JSON.stringify(that.thePlayerAnswer)
				}
			},
			// 抓取自身 玩家信息
			async fetchPlayerL() {
				const res = await getUserSomeMsg(this.$store.state.userInfo.id)
				console.log("自身 玩家信息==>" + JSON.stringify(res))
				this.thePlayerL = JSON.parse(JSON.stringify(res))
				
			},
			//播放、暂停播放音乐start
			clickPlay() {
				if (this.ifMusicPlay) {
					this.innerAudioContext.pause()
					console.log("暂停成功")
					this.ifMusicPlay = false
				} else {
					this.innerAudioContext.play()
					this.ifMusicPlay = true
				}
			},
			//x销毁音乐
			destroyAudio() {
				this.ifMusicPlay = false
				if (this.innerAudioContext) {
					try {
						this.innerAudioContext.pause();
						this.innerAudioContext.destroy()
						this.innerAudioContext = null
					} catch (e) {}
				}
			},
			//开始播放音乐start
			getMusicStart() {
				var that = this
				const innerAudioContext = uni.createInnerAudioContext();
				this.innerAudioContext = innerAudioContext
				innerAudioContext.autoplay = true;
				innerAudioContext.loop = true;
				uni.request({
					url: 'https://v2.api-m.com/api/changya',
					success(res) {
						console.log(res.data.data.song_url)
						that.musicUrl = res.data.data.song_url
						innerAudioContext.src = that.musicUrl
					}
				})

				innerAudioContext.play()

				innerAudioContext.onPlay(() => {
					that.ifMusicPlay = true
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});

			},
			//开始播放音乐end
			//("退出websocket成功")
			giveupMatchFun() {
				uni.closeSocket({
					success: () => {
						console.info("退出成功")
					},
				})


			},
			webSocketClose() {
				uni.websocket.webSocketClose((res) => {
					console.log('WebSocket 关闭', res);
				});
			},

			//确保已经关闭后再重新打开websocket
			getMatchFun() {
				var that = this
				// 创建 WebSocket 连接
				// 确保已经关闭后再重新打开
				var that = this
				if (true) {
					that.socketTask = uni.connectSocket({
						// url: 'ws://' + that.$baseIp + '/wx/chat/' + that.SingleChatMessageDTO.userId,
						url: 'ws://' + that.$baseIp + '/ws/game/' + that.$store.state.userInfo.id,
						success: (res) => {
							console.log('匹配队列中' + res + JSON.stringify(res));

						},
						fail: (err) => {
							console.error('匹配失败:', err);
						}
					})

					that.socketTask.onOpen((res) => {
						console.log("WebSocket连接正常打开中...！");
						that.ifSocketOpen = true
					})
					uni.onSocketError((err) => {
						console.error('WebSocket 错误:', err);
						uni.closeSocket({
							success: () => {
								console.info("退出成功")

							},
						})

					});
					// 监听 WebSocket 接收到消息的事件
					uni.onSocketMessage((res) => {
						console.log('WebSocket 收到消息:', res);


						that.theReturn = JSON.parse(res.data)
						console.log(that.theReturn + "<---That.TheReturn was --->")

					});

					// 监听 WebSocket 错误的事件
					uni.onSocketError((err) => {
						console.error('WebSocket 错误:', err);
						that.webSocketClose()
					});
					that.ifSocketOpen = true
				}
				that.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					that.ifSocketOpen = true
				})
				that.socketTask.onMessage((res) => {
					if (res.data[0] === 'm') {

						console.log("进入这个逻辑，自己答题不会进入的---")
						//如果是对方答题的逻辑
						// 将字符串按照 ":" 进行分割
						const parts = res.data.split(':');
						// 创建一个对象存储键值对
						const obj = {
							[parts[0].trim()]: parseInt(parts[1].trim(), 10) // 使用trim()去除空格，并将字符串转换为数字
						};
						that.$set(that.thePlayerR, 'scoreAll', obj.matcherIntegrl);
					}
					// console.log("收到服务器内容JSON：", JSON.parse(res.data))
					if (JSON.parse(res.data).matcherIntegrl) {
						console.log("进来了matcherIntegrl===》")

					}

					if (JSON.parse(res.data).player) {

						//自己答题才进来的逻辑
						that.firstTime = that.firstTime + 1
						//每次收到这个都会调用一次头像
						if (that.firstTime == 1) {
							that.getUserMsg(JSON.parse(res.data).player.matcherId, JSON.parse(res.data).player
								.integral)

							// 延迟3秒后调用 getPuzzleFun() 函数
							setTimeout(function() {
								that.ifMatch = true
							}, 2000);
						}



						//that.$set(that.thePlayerR, 'scoreAll', JSON.parse(res.data).player.integral);
						console.log("that.thePlayerL.scoreAll===>" + that.thePlayerL.scoreAll)




						//每次调用跟新一次
						that.$set(that.thePlayerL, 'scoreAll', JSON.parse(res.data).player.integral);


						// vm.handleServerMsg(res.data)
						console.log("JSON>PARSE--->" + JSON.parse(res.data))

						//TODO:重连机制
						that.fetchWebSocketMsg = JSON.parse(res.data)
						//由抓取到的puzzleNumber获取对应的谜题 

						var temp = {}
						temp = JSON.parse(res.data)
						if (!that.fetchMsg.scoreAll) {
							that.fetchMsg.scoreAll = parseInt(temp.player.integral)
						}

						that.fromatTime()
						//开始调用函数，生成谜题，进入答题阶段
						//验证题目，收到消息==>，(立即)抓取题目,倒计时\
						that.getPuzzleFun()
						//开始倒计时
						that.startCountdown1()
					} else if (JSON.parse(res.data).reConnect) {
						//重连的逻辑函数
						console.log("玩家正在重连...")
					}
				});
				uni.onSocketError((err) => {
					console.error('WebSocket 错误:', err);
					uni.closeSocket({
						success: () => {
							console.info("退出成功")
						},
					})
				});
			},
			//匹配成功，开始抓取谜题函数start
			async getPuzzleFun() {
				var that = this
				that.setCountdown(15)
				that.isAnswered = false

				if (this.ifSingle) {
					var player = {}
					player.star = Math.floor(Math.random() * 5) + 1
					var fecthSingleMsg = {}
					fecthSingleMsg.player = player
					that.fetchWebSocketMsg = fecthSingleMsg
				}
				console.log(typeof(that.fetchWebSocketMsg) + that.fetchWebSocketMsg.player)
				console.log("that.fetchWebSocketMsg.player.star==>" + that.fetchWebSocketMsg.player.star)
				var Msg = {}
				Msg.star = that.fetchWebSocketMsg.player.star

				try {
					// const res = await checkPuzzleAnswer(that.fetchWebSocketMsg.player.star)

					//由星级获取谜题信息
					const res = await getPuzzleByMsg({
						...Msg
					})
					console.log("抓取谜题:" + JSON.stringify(res))
					// that.fetchMsg = JSON.parse(res)[0]
					const jsonArray = JSON.parse(JSON.stringify(res));


					// //随机取一道谜题

					let randomIndex;
					// do {
					// 	randomIndex = Math.floor(Math.random() * jsonArray.length);
					// } while (that.isIdUsed(jsonArray[randomIndex].id, that.idsHasBeenUsed));

					//题目太少，直接random用上吧
					randomIndex = Math.floor(Math.random() * jsonArray.length);
					that.fetchMsg1 = jsonArray[randomIndex];

					that.idsHasBeenUsed.push(that.fetchMsg1.id);

					//根据获取到的谜题id获取谜题的详细内容
					const res1 = await getPuzzleMoreMsg(that.fetchMsg1.id)
					console.log(JSON.stringify(res1))
					that.fetchMsg = JSON.parse(JSON.stringify(res1))
					that.fetchMsg.optionList.forEach((option, i) => {
						that.$set(that.fetchMsg.optionList, i, {
							...option,
							ifActive: false
						});
					});
				} catch (e) {
					console.log(e)
				}
			},
			//匹配成功，开始抓取谜题函数end

			isIdUsed(id, idsArray) {
				return idsArray.includes(id);
			},

			//调用函数，获取对方玩家的信息start
			async getUserMsg(id, integral) {
				var that = this
				if (that.thePlayerR.scoreAll) {
					that.tempRightScore = parseInt(that.thePlayerR.scoreAll)


				}
				const res = await getUserSomeMsg(id)
				console.log("对方 玩家信息==>" + JSON.stringify(res))
				this.thePlayerR = JSON.parse(JSON.stringify(res))
				if (that.tempRightScore !== 0) {
					that.$set(that.thePlayerR, 'scoreAll', that.tempRightScore);
				}
				if (that.firstTime == 1) {
					that.$set(that.thePlayerR, 'scoreAll', integral);
				}


			},
			//调用函数，获取自身和对方玩家的信息end


			// 监听 WebSocket 接收到消息的事件 函数start
			searchMatch() { // 监听 WebSocket 接收到消息的事件
				var that = this
				uni.onSocketMessage((res) => {
					console.log('WebSocket 收到消息:', res);
					//匹配成功

					that.ifMatch = true //进入匹配页面
					//TODO:重连机制
					that.fetchWebSocketMsg = JSON.parse(res.data)
					//由抓取到的puzzleNumber获取对应的谜题 

					that.getPuzzleFun()

				});

				// 监听 WebSocket 错误的事件
				uni.onSocketError((err) => {
					console.error('WebSocket 错误:', err);
					that.webSocketClose()

				});
			},


			webSocketClose() {


				uni.onSocketOpen(function() {
					uni.closeSocket();
				});


			},
			closeSocket() {

				uni.closeSocket({
					success: () => {
						console.info("退出成功")
					},
				})
			},


			//验证题目
			async sendMsg(type) {
				var that = this

				that.setCountdown(15)
				//this.startGlobalCountdown()
				// that.countdown = 15
				that.isAnswered = false

				if (this.ifSingle) {
					//单人赛提交答案
					if (that.fetchMsg.puzzleAnswer === this.answer) {
						console.log("玩家答对了...")
						that.rightNumber += 1;
					} else {
						console.log("玩家答错了...")
						that.wrongNumber += 1;
					}
					//重新抓取题目
					that.getPuzzleFunSingle()
					this.answer = '' //清空答案
				} else {
					//双人赛提交答案

					var Msg1 = {}

					// const res1 = await checkPuzzleAnswer(Msg1)
					Msg1.isSuccess = 0
					Msg1.puzzleId = that.fetchMsg1.id //谜题id
					Msg1.userId = that.$store.state.userInfo.id //玩家id
					// Msg1.buffs = that.buffs
					if (this.ifBuffGame) {
						//道具赛
						// Msg1.buffs = ['addTime']
						if (this.canChoose) {

							Msg1.buffs = [this.buffWhich];
							if (Msg1.buffs[0] === '') {
								Msg1.buffs = []
							}


						}



					}

					Msg1.clueNumber = 0
					Msg1.ranking = 1

					if (type === 1) {
						//说明是时间到了自动提交的
						Msg1.result = '' //玩家答题结果
						that.sendSocketMessage(Msg1) //发送websocket消息
					} else {
						//发送消息到websocket				

						Msg1.result = that.answer //玩家答题结果


					}
					that.sendSocketMessage(Msg1) //发送websocket消息
					that.canChoose = false;//不再进行道具的使用
				}


				//that.getPuzzleFun()//抓取新的谜题
			},

			// 发送 WebSocket 消息
			async sendSocketMessage(msg) {
				var that = this
				//msg信息
				await uni.sendSocketMessage({
					// data: msg,
					data: JSON.stringify({
						...msg
					}),
					msg,
					success: async (msg) => {
						console.log('WebSocket 发送消息:', msg);
					},
					fail(err) {
						console.log('WebSocket 发送消息失败:', err);
					}
				});

				that.answer = '' //清空答案
				that.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					that.ifSocketOpen = true
				})
				uni.onSocketError((err) => {
					console.error('WebSocket 错误:', err);
					uni.closeSocket({
						success: () => {
							console.info("退出成功")
						},
					})

				});

			},

			handleKeyboardHeightChange(e) {
				console.log('keyboard height change:', e.height)
				this.keyboardHeight = e.height
			},
		},
	}
</script>
<style lang="scss" scoped>
	@import './matchToSolve.scss';
</style>